// 闲置物品详情页面逻辑
const NeighborhoodAPI = require('../../../../js/services/api/neighborhoodService');

// 日期格式化工具函数
function formatDate(dateString) {
  if (!dateString) return '';
  
  // 检查是否已经是正确格式
  if (dateString.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)) {
    return dateString;
  }
  
  // 处理ISO格式日期
  if (dateString.includes('T')) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  
  // 处理纯日期格式
  if (dateString.match(/^\d{4}-\d{2}-\d{2}$/)) {
    return dateString + ' 00:00:00';
  }
  
  return dateString;
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    itemDetail: {},
    itemId: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const itemId = options.id;
    this.setData({ itemId });
    
    wx.setNavigationBarTitle({
      title: '物品详情'
    });
    
    this.loadItemDetail(itemId);
  },

  /**
   * 加载物品详情
   */
  loadItemDetail: function(itemId) {
    wx.showLoading({ title: '加载中...' });
    
    // 调用API获取物品详情
    NeighborhoodAPI.getIdleItemDetail(itemId)
      .then(res => {
        if (res.success) {
          const itemDetail = res.data;
          
          // 格式化日期字段
          itemDetail.createTime = formatDate(itemDetail.createTime);
          if (itemDetail.borrowDuration) {
            itemDetail.borrowDuration = formatDate(itemDetail.borrowDuration);
          }
          
          this.setData({
            itemDetail: itemDetail
          });
        } else {
          wx.showToast({ title: '获取物品详情失败', icon: 'none' });
        }
      })
      .catch(err => {
        console.error('获取物品详情失败:', err);
        wx.showToast({ title: '网络异常', icon: 'none' });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  /**
   * 拨打电话
   */
  makePhoneCall: function() {
    const phoneNumber = this.data.itemDetail.contactInfo.replace(/\*/g, '');
    wx.makePhoneCall({
      phoneNumber: phoneNumber,
      fail: () => {
        wx.showToast({ title: '拨号失败', icon: 'none' });
      }
    });
  },

  /**
   * 申请借用
   */
  borrowItem: function() {
    const item = this.data.itemDetail;
    
    wx.showModal({
      title: '申请借用',
      content: `确定要申请借用"${item.itemName}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.submitBorrowRequest(item);
        }
      }
    });
  },

  /**
   * 提交借用申请
   */
  submitBorrowRequest: function(item) {
    wx.showLoading({ title: '提交申请中...' });
    
    const borrowData = {
      itemId: item.id,
      itemName: item.itemName,
      borrowDuration: item.borrowDuration,
      contactInfo: item.contactInfo
    };

    NeighborhoodAPI.borrowItem(borrowData)
      .then(res => {
        if (res.success) {
          wx.showToast({ 
            title: res.message, 
            icon: 'success',
            duration: 2000
          });
        } else {
          wx.showToast({ title: res.message || '申请失败', icon: 'none' });
        }
      })
      .catch(err => {
        console.error('借用申请失败:', err);
        wx.showToast({ title: '网络异常，申请失败', icon: 'none' });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  /**
   * 分享物品
   */
  shareItem: function() {
    const item = this.data.itemDetail;
    
    wx.showActionSheet({
      itemList: ['分享给好友', '生成分享海报'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 分享给好友
          wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
          });
        } else if (res.tapIndex === 1) {
          // 生成分享海报
          wx.showToast({ title: '海报功能开发中', icon: 'none' });
        }
      }
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const item = this.data.itemDetail;
    return {
      title: `邻里互助：${item.itemName}`,
      path: `/pages/neighborhood-help/idle-sharing/detail?id=${item.id}`,
      imageUrl: item.imageUrl || '/img/tabbar_resource.png'
    };
  },

  /**
   * 图片加载错误处理
   */
  onImageError: function() {
    const { itemDetail } = this.data;
    // 只有当当前图片不是默认图片时才替换
    if (itemDetail.imageUrl !== '/img/tabbar_resource.png') {
      this.setData({
        'itemDetail.imageUrl': '/img/tabbar_resource.png'
      });
    }
  }
});